package com.saltedfish.tool.util;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.CalendarContract;
import android.text.TextUtils;
import com.saltedfish.tool.model.SmallTable;
import com.saltedfish.tool.model.WeekInfo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import cn.droidlover.xdroidmvp.log.XLog;

public class CalendarReminderUtils {

    private static String CALENDER_URL = "content://com.android.calendar/calendars";
    private static String CALENDER_EVENT_URL = "content://com.android.calendar/events";
    private static String CALENDER_REMINDER_URL = "content://com.android.calendar/reminders";

    private static String CALENDARS_NAME = "flag";
    private static String CALENDARS_ACCOUNT_NAME = "flag.com";
    private static String CALENDARS_ACCOUNT_TYPE = "com.android.boohee";
    private static String CALENDARS_DISPLAY_NAME = "flag账户";

    /**
     * 检查是否已经添加了日历账户，如果没有添加先添加一个日历账户再查询
     * 获取账户成功返回账户id，否则返回-1
     */
    private static int checkAndAddCalendarAccount(Context context) {
        int oldId = checkCalendarAccount(context);
        if( oldId >= 0 ){
            return oldId;
        }else{
            long addId = addCalendarAccount(context);
            if (addId >= 0) {
                return checkCalendarAccount(context);
            } else {
                return -1;
            }
        }
    }

    /**
     * 检查是否存在现有账户，存在则返回账户id，否则返回-1
     */
    private static int checkCalendarAccount(Context context) {
        Cursor userCursor = context.getContentResolver().query(Uri.parse(CALENDER_URL), null, null, null, null);
        try {
            if (userCursor == null) { //查询返回空值
                return -1;
            }
            int count = userCursor.getCount();
            if (count > 0) { //存在现有账户，取第一个账户的id返回
                userCursor.moveToFirst();
                return userCursor.getInt(userCursor.getColumnIndex(CalendarContract.Calendars._ID));
            } else {
                return -1;
            }
        } finally {
            if (userCursor != null) {
                userCursor.close();
            }
        }
    }

    /**
     * 添加日历账户，账户创建成功则返回账户id，否则返回-1
     */

    private static long addCalendarAccount(Context context) {
        TimeZone timeZone = TimeZone.getDefault();
        ContentValues value = new ContentValues();
        value.put(CalendarContract.Calendars.NAME, CALENDARS_NAME);
        value.put(CalendarContract.Calendars.ACCOUNT_NAME, CALENDARS_ACCOUNT_NAME);
        value.put(CalendarContract.Calendars.ACCOUNT_TYPE, CALENDARS_ACCOUNT_TYPE);
        value.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, CALENDARS_DISPLAY_NAME);
        value.put(CalendarContract.Calendars.VISIBLE, 1);
        value.put(CalendarContract.Calendars.CALENDAR_COLOR, Color.BLUE);
        value.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
        value.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
        value.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, timeZone.getID());
        value.put(CalendarContract.Calendars.OWNER_ACCOUNT, CALENDARS_ACCOUNT_NAME);
        value.put(CalendarContract.Calendars.CAN_ORGANIZER_RESPOND, 0);

        Uri calendarUri = Uri.parse(CALENDER_URL);
        calendarUri = calendarUri.buildUpon()
                .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, CALENDARS_ACCOUNT_NAME)
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CALENDARS_ACCOUNT_TYPE)
                .build();

        Uri result = context.getContentResolver().insert(calendarUri, value);
        long id = result == null ? -1 : ContentUris.parseId(result);
        return id;
    }

    /**
     * 添加日历事件
     */
    public static String addCalendarEvent(Context context, SmallTable smallTable) {
        if (context == null) {
            return "";
        }
        int calId = checkAndAddCalendarAccount(context); //获取日历账户的id
        if (calId < 0) { //获取账户id失败直接返回，添加日历事件失败
            return "";
        }
        ContentValues event = new ContentValues();

        //添加日历事件
        Calendar mCalendar = Calendar.getInstance();
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String[] repeatTimes = smallTable.repeatTime.split("-");
        String endDay = "";

        try {
            String startTime = smallTable.startTime + " "+ repeatTimes[0];
            mCalendar.setTimeInMillis(myFormatter.parse(startTime).getTime());//设置开始时间
            long start = mCalendar.getTime().getTime();
            String endTime = smallTable.startTime + " "+ repeatTimes[1];
            mCalendar.setTimeInMillis(myFormatter.parse(endTime).getTime());//设置终止时间，开始时间加10分钟
            long end = mCalendar.getTime().getTime();
            event.put(CalendarContract.Events.DTSTART, start);
            event.put(CalendarContract.Events.DTEND, end);

            endDay = smallTable.endTime.replace("-","") + "T"+  repeatTimes[1].replace(":","") +"00Z;";
//            XLog.e("-----endDay----"+endDay);
        } catch (Exception e) {
        }


        event.put("title", smallTable.title);
        event.put("_id", smallTable.subId);
        event.put("description", "提醒时间："+smallTable.repeatTime);
        event.put("calendar_id", calId); //插入账户的id

        if(!TextUtils.isEmpty(smallTable.repeatDay)){
            String repeatDay =  smallTable.repeatDay.replace(" ",",");
            String[] weeks = repeatDay.split(",");
            List<String> list = new ArrayList<>();
            for (String week : weeks) {
                if(week.equals("周一")){
                list.add("MO");
//                    repeatDay.replace("周一","MO");
                }else  if(week.equals("周二")){
                list.add("TU");
//                    repeatDay.replace("周二","TU");
                }else if(week.equals("周三")){
                list.add("WE");
//                    repeatDay.replace("周三","WE");
                }else if(week.equals("周四")){
                list.add("TH");
//                    repeatDay.replace("周四","TH");
                }else if(week.equals("周五")){
                list.add("FR");
//                    repeatDay.replace("周五","FR");
                }else if(week.equals("周六")){
                list.add("SA");
//                    repeatDay.replace("周六","SA");
                }else if(week.equals("周日")){
                list.add("SU");
//                    repeatDay.replace("周日","SU");
                }
            }
            String dyDay = "";
            for (int i =0 ;i<list.size();i++) {
                list.get(i);
                    if(i == 0){
                        dyDay = list.get(0);
                    }else {
                        dyDay = dyDay + "," + list.get(i);
                    }
            }

            event.put(CalendarContract.Events.RRULE, "FREQ=WEEKLY;UNTIL="+endDay+"WKST=SU;BYDAY="+dyDay);

        }

        event.put(CalendarContract.Events.HAS_ALARM, 1);//设置有闹钟提醒
        event.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());//这个是时区，必须有
        Uri newEvent = context.getContentResolver().insert(Uri.parse(CALENDER_EVENT_URL), event); //添加事件
        if (newEvent == null) { //添加日历事件失败直接返回
            return "";
        }
       // XLog.e("-----事件提醒的设定---EVENT_ID--"+ContentUris.parseId(newEvent));
        //事件提醒的设定
        ContentValues values = new ContentValues();
        String eventId = ContentUris.parseId(newEvent) + "";
        values.put(CalendarContract.Reminders.EVENT_ID, ContentUris.parseId(newEvent));
        values.put(CalendarContract.Reminders.MINUTES, 0);// 提前previousDate天有提醒
        values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
        Uri uri = context.getContentResolver().insert(Uri.parse(CALENDER_REMINDER_URL), values);
      //  XLog.e("--日历---事件提醒的设定-----"+values.toString());
        if(uri == null) { //添加事件提醒失败直接返回
            return "";
        }

        return  eventId;
    }


    /**
     * 修改日历事件
     */
    public static void updateCalendarEvent(Context context, SmallTable smallTable) {
        if (context == null) {
            return ;
        }
//        int calId = checkAndAddCalendarAccount(context); //获取日历账户的id
//        if (calId < 0) { //获取账户id失败直接返回，添加日历事件失败
//            return ;
//        }
        ContentValues event = new ContentValues();

        //添加日历事件
        Calendar mCalendar = Calendar.getInstance();
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String[] repeatTimes = smallTable.repeatTime.split("-");
        String endDay = "";

        try {
            String startTime = smallTable.startTime + " "+ repeatTimes[0];
            mCalendar.setTimeInMillis(myFormatter.parse(startTime).getTime());//设置开始时间
            long start = mCalendar.getTime().getTime();
            String endTime = smallTable.startTime + " "+ repeatTimes[1];
            mCalendar.setTimeInMillis(myFormatter.parse(endTime).getTime());//设置终止时间，开始时间加10分钟
            long end = mCalendar.getTime().getTime();
            event.put(CalendarContract.Events.DTSTART, start);
            event.put(CalendarContract.Events.DTEND, end);
            endDay = smallTable.endTime.replace("-","") + "T"+  repeatTimes[1].replace(":","") +"00Z;";

        } catch (Exception e) {
        }

        event.put("title", smallTable.title);
        event.put("_id", smallTable.subId);
        event.put("description", "提醒时间："+smallTable.repeatTime);
//        event.put("calendar_id", calId); //插入账户的id

        if(!TextUtils.isEmpty(smallTable.repeatDay)){
            String repeatDay =  smallTable.repeatDay.replace(" ",",");
            String[] weeks = repeatDay.split(",");
            List<String> list = new ArrayList<>();
            for (String week : weeks) {
                if(week.equals("周一")){
                    list.add("MO");
//                    repeatDay.replace("周一","MO");
                }else  if(week.equals("周二")){
                    list.add("TU");
//                    repeatDay.replace("周二","TU");
                }else if(week.equals("周三")){
                    list.add("WE");
//                    repeatDay.replace("周三","WE");
                }else if(week.equals("周四")){
                    list.add("TH");
//                    repeatDay.replace("周四","TH");
                }else if(week.equals("周五")){
                    list.add("FR");
//                    repeatDay.replace("周五","FR");
                }else if(week.equals("周六")){
                    list.add("SA");
//                    repeatDay.replace("周六","SA");
                }else if(week.equals("周日")){
                    list.add("SU");
//                    repeatDay.replace("周日","SU");
                }
            }
            String dyDay = "";
            for (int i =0 ;i<list.size();i++) {
                list.get(i);
                if(i == 0){
                    dyDay = list.get(0);
                }else {
                    dyDay = dyDay + "," + list.get(i);
                }
            }

            event.put(CalendarContract.Events.RRULE, "FREQ=WEEKLY;UNTIL="+endDay+"WKST=SU;BYDAY="+dyDay);

        }
        try {
            Uri  updateUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, Long.parseLong(smallTable.subId));
            int rows = context.getContentResolver().update(updateUri, event, null, null);
//        XLog.e("---事件修改反馈------>>"+rows);
            if (rows == -1) { //事件修改失败
                return;
            }
        }catch (Exception e){

        }


    }


    /**
     * 修改单次日历事件
     */
    public static void updateOneCalendarEvent(Context context, String day,String repeatTime,String subId) {
        if (context == null) {
            return ;
        }
//        int calId = checkAndAddCalendarAccount(context); //获取日历账户的id
//        if (calId < 0) { //获取账户id失败直接返回，添加日历事件失败
//            return ;
//        }
        ContentValues event = new ContentValues();

        //添加日历事件
        Calendar mCalendar = Calendar.getInstance();
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String[] repeatTimes = repeatTime.split("-");
        try {
            String startTime = day + " "+ repeatTimes[0];
            mCalendar.setTimeInMillis(myFormatter.parse(startTime).getTime());//设置开始时间
            long start = mCalendar.getTime().getTime();
            String endTime = day + " "+ repeatTimes[1];
            mCalendar.setTimeInMillis(myFormatter.parse(endTime).getTime());//设置终止时间，开始时间加10分钟
            long end = mCalendar.getTime().getTime();
            event.put(CalendarContract.Events.DTSTART, start);
            event.put(CalendarContract.Events.DTEND, end);
        } catch (Exception e) {
        }

//        event.put("title", smallTable.title);
        event.put("_id", subId);
 //       event.put("description", "提醒时间："+smallTable.repeatTime);
//        event.put("calendar_id", calId); //插入账户的id

        Uri  updateUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, Long.parseLong(subId));
        int rows = context.getContentResolver().update(updateUri, event, null, null);
        XLog.e("---事件修改反馈------>>"+rows);
        if (rows == -1) { //事件修改失败
            return;
        }

    }

    /**
     * 删除日历事件
     */
    public static void deleteCalendarEvent(Context context,String subId) {
        if (context == null) {
            return;
        }
        Cursor eventCursor = context.getContentResolver().query(Uri.parse(CALENDER_EVENT_URL), null, null, null, null);
        try {
            if (eventCursor == null) { //查询返回空值
                return;
            }
            if (eventCursor.getCount() > 0) {
                //遍历所有事件，找到title跟需要查询的title一样的项
                for (eventCursor.moveToFirst(); !eventCursor.isAfterLast(); eventCursor.moveToNext()) {
                    String eventId = eventCursor.getString(eventCursor.getColumnIndex(CalendarContract.Events._ID));
//                    XLog.e(eventId+"------sub_id-------"+subId);
                    if (!TextUtils.isEmpty(eventId) && eventId.equals(subId)) {
//                        int id = eventCursor.getInt(eventCursor.getColumnIndex(CalendarContract.Calendars._ID));//取得id
 //                       Uri deleteUri = ContentUris.withAppendedId(Uri.parse(CALENDER_EVENT_URL), id);

                        try {
                            Uri deleteUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, Long.parseLong(subId));
//                        XLog.e(id+"------deleteUri-------"+deleteUri);
                            int rows = context.getContentResolver().delete(deleteUri, null, null);
                            if (rows == -1) { //事件删除失败
                                return;
                            }
                        }catch (Exception e){

                        }

                    }
                }
            }
        } finally {
            if (eventCursor != null) {
                eventCursor.close();
            }
        }
    }



}
